<?php
require_once 'database21.php';

class Course {
    private $db;
    
    public function __construct() {
        $this->db = new Database();
    }
    
    // 获取所有课程
    public function getCourses() {
        $sql = "SELECT c.course_id, c.course_name, c.teacher_id, c.credit, t.teacher_name 
                FROM courses c 
                LEFT JOIN teachers t ON c.teacher_id = t.teacher_id 
                ORDER BY c.course_id";
        return $this->db->query($sql);
    }
    
    // 获取单个课程
    public function getCourse($id) {
        $sql = "SELECT * FROM courses WHERE course_id = ?";
        $result = $this->db->query($sql, [$id]);
        return $result ? $result[0] : null;
    }
    
    // 创建课程
    public function createCourse($name, $teacher_id, $credit) {
        // 如果teacher_id为空，设置为NULL
        if (empty($teacher_id)) {
            $teacher_id = null;
        }
        
        $sql = "INSERT INTO courses (course_name, teacher_id, credit) VALUES (?, ?, ?)";
        return $this->db->execute($sql, [$name, $teacher_id, $credit]);
    }
    
    // 更新课程
    public function updateCourse($id, $name, $teacher_id, $credit) {
        // 如果teacher_id为空，设置为NULL
        if (empty($teacher_id)) {
            $teacher_id = null;
        }
        
        $sql = "UPDATE courses SET course_name = ?, teacher_id = ?, credit = ? WHERE course_id = ?";
        return $this->db->execute($sql, [$name, $teacher_id, $credit, $id]);
    }
    
    // 删除课程
    public function deleteCourse($id) {
        // 检查是否有关联的成绩记录
        $sql = "SELECT COUNT(*) as count FROM scores WHERE course_id = ?";
        $result = $this->db->query($sql, [$id]);
        if ($result[0]['count'] > 0) {
            throw new Exception("该课程有关联的成绩记录，无法删除");
        }
        
        // 检查是否有关联的授课记录
        $sql = "SELECT COUNT(*) as count FROM teaching WHERE course_id = ?";
        $result = $this->db->query($sql, [$id]);
        if ($result[0]['count'] > 0) {
            throw new Exception("该课程有关联的授课记录，无法删除");
        }
        
        $sql = "DELETE FROM courses WHERE course_id = ?";
        return $this->db->execute($sql, [$id]);
    }
    
    // 获取所有教师
    public function getTeachers() {
        $sql = "SELECT t.teacher_id, t.teacher_name, d.department_name 
                FROM teachers t 
                LEFT JOIN departments d ON t.department_id = d.department_id 
                ORDER BY t.teacher_name";
        return $this->db->query($sql);
    }
}
?>